<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert
        title="添加商品信息"
        type="info"
        show-icon
        :closable='false'>
      </el-alert>
      <!-- steps步骤条  字符串转数字 -0 -->
      <el-steps align-center :space="200" :active="activeIndex - 0" finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab标签表单 name会绑定到v-model  -->
      <el-form :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position='top'>
        <el-tabs @tab-click='tabClicked()' :before-leave='beforeTabLeave' v-model="activeIndex" :tab-position="'left'">
          <el-tab-pane name='0' label="基本信息">
            <!-- 渲染表单信息 -->
            <el-form-item label='商品名称' prop='goods_name'>
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label='商品价格' prop='goods_price'>
              <el-input type='number' v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label='商品重量' prop='goods_weight'>
              <el-input type='number' v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label='商品数量' prop='goods_number'>
              <el-input type='number' v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label='商品分类' prop='goods_cat'>
              <span>选择商品分类:</span>
                <el-cascader
                  clearable
                  v-model="addForm.goods_cat"
                  :options="cateList"
                  :props= "cascaderProps" @change="handleChange()"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name='1' label="商品参数">
            <!-- 渲染表单item项 -->
            <el-form-item :key="item.attr_id" v-for="(item) in manyTabData" :label='item.attr_name'>
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :key="index" v-for="(checkboxitem, index) in item.attr_vals" :label="checkboxitem"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name='2' label="商品属性">
            <el-form-item :label='item.attr_name' :key="item.attr_id" v-for="item in onlyTabData">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name='3' label="商品图片">
            <el-upload
              :on-success='picUploadSuccess'
              :headers='headerObj'
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane name='4' label="商品内容">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <el-button @click="addGoods()" type='primary' style="margin-top: 10px">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览对话框 -->
    <el-dialog
      title="图片预览"
      :visible.sync="picPreviewDialogVisible"
      width="50%">
      <img width="100%" :src="previewPath">
    </el-dialog>
  </div>
</template>
<script>
import _ from 'lodash'
export default {
  data () {
    return {
      // 当前点击的索引
      activeIndex: '0',
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品所属分类数组
        goods_cat: [],
        pics: [],
        // 商品详情
        goods_introduce: '',
        // 商品的参数（数组），包含 `动态参数` 和 `静态属性`
        attrs: []
      },
      addFormRules: {
        goods_name: [
          { required: true, message: '必填商品名称', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '必填商品价格', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '必填商品重量', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '必填商品数量', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      // 商品分类列表
      cateList: [],
      // 级联选择框配置对象
      cascaderProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 动态参数列表
      manyTabData: [],
      // 静态属性列表
      onlyTabData: [],
      // 图片上传地址
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 图片上传不是axios请求 需要自己指定请求头header
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 图片预览路径
      previewPath: '',
      // 图片预览对话框的显示隐藏
      picPreviewDialogVisible: false
    }
  },
  created () {
    this.getCateList()
  },
  computed: {
    // 拿到请求参数列表的id 分类id 最后一项
    cateId () {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  },
  methods: {
    // 获取所有商品分类数据
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据失败!')
      }
      this.cateList = res.data
      // console.log(this.cateList)
    },
    // 级联框改变函数
    handleChange () {
      console.log(this.addForm.goods_cat)
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // 标签页跳转
    beforeTabLeave (activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.info('请先选中分类')
        // return false会阻止标签页跳转
        return false
      }
    },
    async tabClicked () {
      console.log(this.activeIndex)
      // this.activeIndex === '1'说明访问的是商品参数tab栏
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: 'many'
          }
        })
        if (res.meta.status !== 200) return this.$message.error('获取动态参数列表失败')
        // 把attr_vals属性处理成数组供多选栏使用
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyTabData = res.data
        console.log(this.manyTabData)
      }
      if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: 'only'
          }
        })
        if (res.meta.status !== 200) return this.$message.error('获取静态属性列表失败')
        this.onlyTabData = res.data
      }
    },
    // 图片预览 形参为自带
    handlePreview (file) {
      // console.log(file)
      this.previewPath = file.response.data.url
      this.picPreviewDialogVisible = true
    },
    // 移除图片
    handleRemove (file) {
      // console.log(file)
      // 获取删除图片的路径
      const filePath = file.response.data.tmp_path
      const needDeleteIndex = this.addForm.pics.findIndex(value => value.pics === filePath)
      this.addForm.pics.splice(needDeleteIndex, 1)
      console.log(this.addForm)
    },
    // 图片上传成功的事件  response为服务器返回的数据
    picUploadSuccess (response) {
      // console.log(response)
      // 拼接图片对象
      const picsTmpPath = { pics: response.data.tmp_path }
      // 传到form表单
      this.addForm.pics.push(picsTmpPath)
      console.log(this.addForm)
    },
    // 添加商品按钮
    addGoods () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('表单验证失败')
        // 执行添加商品
        // 深拷贝 为了处理级联选择框goods_cat必须是数组 但服务请求需要是字符串
        const cloneAddForm = _.cloneDeep(this.addForm)
        cloneAddForm.goods_cat = cloneAddForm.goods_cat.join(',')
        // 处理动态参数和静态属性
        this.manyTabData.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals.join(' ') }
          this.addForm.attrs.push(newInfo)
        })
        this.onlyTabData.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
          this.addForm.attrs.push(newInfo)
        })
        cloneAddForm.attrs = this.addForm.attrs
        console.log(cloneAddForm)
        // 添加商品请求
        const { data: res } = await this.$http.post('goods', cloneAddForm)
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        // 跳转到商品列表 商品列表已经自动刷新
        this.$router.push('/goods')
      })
    }
  }
}
</script>
<style lang="less" scoped>
.el-checkbox {
  margin: 0 5px 0 0 !important;
}
</style>
